package com.itqn.servlet;

import com.alibaba.fastjson.JSONArray;
import com.itqn.pojo.Category;
import com.itqn.pojo.PageBean;
import com.itqn.service.CategoryService;
import com.itqn.service.Impl.CategoryServiceImpl;
import lombok.SneakyThrows;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;

@WebServlet(value = "/categoryQuery")
public class CategoryQueryServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }

    @SneakyThrows
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
        // 解决post提交中文乱码
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=UTF-8");

        //获取参数
        String name = request.getParameter("name");
        Integer page = Integer.valueOf(request.getParameter("page"));
        page = page == null ? 1 : page;
        Integer pageSize = Integer.valueOf(request.getParameter("pageSize"));
        pageSize = pageSize == null ? 5 : pageSize;
        // 创建业务逻辑层对象
        CategoryService categoryService=new CategoryServiceImpl();
        PageBean<Category> pageQuery = categoryService.query(name, pageSize, page);
        String str = JSONArray.toJSONString(pageQuery);
        PrintWriter writer = response.getWriter();
        writer.write(str);
    }
}